import { fetchEventSource } from "@microsoft/fetch-event-source";
import { getToken } from '@/utils/auth'
const ctrl = new AbortController();
const APIURl = 'https://api.bytesbay.cn'
export default class CustomEventSource {
    message: any;
    url: any;
    method: string;
    data: any;
    open: any;
    close: any;
    error: any;

    constructor(opitons:any) {     
      this.url = opitons.url || "";
      this.message = opitons.message;
      this.method = opitons.method || "POST";
      this.data = opitons.data || {};
      this.open = opitons.open || null;
      this.close = opitons.close || null;
      this.error = opitons.error || null;
      const token = getToken() || ''
      const _this = this
      fetchEventSource(APIURl + "" + this.url, {
        method: this.method,
        headers:{
          "Content-Type": "application/json",
          'token': token
        },
        body: JSON.stringify(this.data),
        signal: ctrl.signal,
        openWhenHidden: true,
        async onopen(response) {
          // console.log("onopen", response);
          _this.open && _this.open(response);
        },
        onmessage(msg) {
          // console.log("onmessage", msg);
          _this.message && _this.message(msg);
        },
        onclose() {
          console.log("onclose");
          _this.close && _this.close();
        },
        onerror(err) {
          // console.log("onerror", err);
          _this.error && _this.error(err);
          ctrl.abort();
          throw err;
        },
      });
    }
}